<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <el-button type="primary" @click="toAdd">+ 添加</el-button>
            </div>
        </template>
        <!-- 表格 -->
        <el-table :data="trademarkList" border style="width: 100%">
            <el-table-column type="index" label="序号" width="100" align="center">
            </el-table-column>
            <el-table-column prop="tmName" label="品牌" width="180">
            </el-table-column>
            <el-table-column prop="name" label="品牌Logo">
                <template v-slot="{ row }">
                    <img :src="row.logoUrl" alt="" style="width:100px;height:100px">
                </template>
            </el-table-column>
            <el-table-column prop="address" label="操作">
                <template v-slot="{ row }">
                    <el-button type="warning" size="small" icon="el-icon-edit" @click="toEdit(row)" />
                    <el-button type="danger" size="small" icon="el-icon-delete" @click="toDelete(row)" />
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[3, 6, 9, 12]" :page-size="pageSize" layout="prev, pager, next, jumper,->,sizes,total "
            :total="total" style="margin-top: 20px;">
        </el-pagination>
        <!-- 添加弹出框 -->
        <el-dialog :visible.sync="dialogFormVisible" :title="`${trademarkInfo.id ? '修改' : '添加'}品牌`">
            <el-form :model="trademarkInfo" ref="trademarkRef" :rules="rules">
                <el-form-item label="品牌名称" label-width="100px" prop="tmName">
                    <el-input v-model="trademarkInfo.tmName" autocomplete="off" />
                </el-form-item>
                <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
                    <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/fileUpload`"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="btnTrademark('trademarkRef')">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>


<script>
import { reqGetAllTrademarkListData, reqAddTrademark, reqDeleteTrademark, reqUpdateTrademark } from '@/api/product/trademark'
export default {
    name: 'trademark',
    data() {
        return {
            trademarkList: [],
            currentPage: 1, //当前页
            pageSize: 3, //每页显示条数
            total: 0,//品牌列表数据总条数
            dialogFormVisible: false,
            trademarkInfo: {
                tmName: "", //品牌名称
                logoUrl: "", //品牌图片地址
            },//品牌信息
            imageUrl: '',
            BASE_URL: process.env.VUE_APP_BASE_API,
            rules: {
                tmName: [
                    { required: true, message: "请添加品牌名称", trigger: "blur" },
                    { min: 2, max: 6, message: "长度在2到6之间", trigger: "blur" },
                ],
                logoUrl: [
                    { required: true, message: "请选择要上传的图片", trigger: "change" },
                ],
            },
        }
    },
    methods: {
        //每页显示数量改变时
        handleSizeChange(val) {
            this.pageSize = val
            this.getTrademarkList()
            // console.log(`每页 ${val} 条`);
        },
        //当前页改变时
        handleCurrentChange(val) {
            this.currentPage = val
            this.getTrademarkList()
            // console.log(`当前页: ${val}`);
        },

        //获取品牌数据列表
        async getTrademarkList() {
            const result = await reqGetAllTrademarkListData(this.currentPage, this.pageSize)
            // console.log(result)
            this.trademarkList = result.data.records
            this.total = result.data.total
        },

        //上传图片成功
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            // console.log(this.imageUrl)
            this.trademarkInfo.logoUrl = res.data
            // console.log(res)
            this.$refs.trademarkRef.clearValidate(['logoUrl'])
        },

        //上传图片前的校验
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },

        //添加
        toAdd() {
            this.dialogFormVisible = true

            //清空原form中的信息
            this.trademarkInfo = {
                tmName: "", //品牌名称
                logoUrl: "", //品牌图片地址
            }

            this.imageUrl = "";
        },

        //提交表单信息并验证
        //新增trademark 或者 更新trademark
        btnTrademark(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    if (this.trademarkInfo.id) {
                        await reqUpdateTrademark(this.trademarkInfo)
                        this.$message.success('更新成功')
                    } else {
                        await reqAddTrademark(this.trademarkInfo)
                        this.$message.success('添加成功')
                    }

                    this.dialogFormVisible = false
                    this.getTrademarkList()
                    // console.log('rr1')
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        //删除品牌
        toDelete(row) {
            this.$confirm(`确定删除${row.tmName}吗`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                await reqDeleteTrademark(row.id)
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.getTrademarkList()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },

        //编辑品牌
        toEdit(row) {
            // console.log(row)
            this.dialogFormVisible = true
            Object.assign(this.trademarkInfo, row)
            this.imageUrl = this.trademarkInfo.logoUrl
        }



    },
    mounted() {
        this.getTrademarkList()
    }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>